//
//  CALayer+AD.swift
//  ADKit
//
//  Created by Adoma on 2023/12/26.
//

import UIKit

public extension CAGradientLayer {
    
    /// 从上到下
    /// by ADKit
    convenience init(vertical colors: [UIColor]) {
        self.init()
        self.colors = colors.compactMap({ $0.cgColor })
        self.locations = [0,1]
        self.startPoint = CGPoint.zero
        self.endPoint = CGPoint(x: 0, y: 1)
    }
    
    /// 从左到右
    /// by ADKit
    convenience init(horizontal colors: [UIColor]) {
        self.init()
        self.colors = colors.compactMap({ $0.cgColor })
        self.locations = [0,1]
        self.startPoint = CGPoint.zero
        self.endPoint = CGPoint(x: 1, y: 0)
    }
}

public class ADGradientView: UIView {
    
    public let locations: [NSNumber]
    public let colors: [CGColor]
    public let startPoint: CGPoint
    public let endPoint: CGPoint
    
    public var lineWidth: CGFloat = 0 {
        didSet {
            setNeedsLayout()
        }
    }

    public convenience init(horizontal colors: [UIColor], locations: [NSNumber] = [0,1]) {
        self.init(colors: colors, locations: locations, startPoint: .zero, endPoint: CGPoint(x: 1, y: 0))
    }
    
    public convenience init(vertical colors: [UIColor], locations: [NSNumber] = [0,1]) {
        self.init(colors: colors, locations: locations, startPoint: .zero, endPoint: CGPoint(x: 0, y: 1))
    }
    
    public init(colors: [UIColor], locations: [NSNumber], startPoint: CGPoint, endPoint: CGPoint) {
        self.locations = locations
        self.colors = colors.compactMap({ $0.cgColor })
        self.startPoint = startPoint
        self.endPoint = endPoint
        super.init(frame: .zero)
    }
    
    required init?(coder: NSCoder) {
        self.colors = [UIColor.white.cgColor]
        self.locations = [0,1]
        self.startPoint = .zero
        self.endPoint = .init(x: 1, y: 1)
        super.init(coder: coder)
    }
    
    public override class var layerClass: AnyClass {
        return CAGradientLayer.self
    }
    
    public override func layoutSubviews() {
        super.layoutSubviews()
        
        guard let gradientLayer = layer as? CAGradientLayer else { return }
        gradientLayer.colors = self.colors
        gradientLayer.locations = self.locations
        gradientLayer.startPoint = self.startPoint
        gradientLayer.endPoint = self.endPoint
        
        if lineWidth > 0 {
            let maskLayer = CAShapeLayer()
            maskLayer.lineWidth = lineWidth
            maskLayer.path = UIBezierPath(roundedRect: CGRect(x: lineWidth / 2, y: lineWidth / 2, width: bounds.width - lineWidth, height: bounds.height - lineWidth), cornerRadius: gradientLayer.cornerRadius).cgPath
            maskLayer.fillColor = UIColor.clear.cgColor
            maskLayer.strokeColor = UIColor.black.cgColor
            gradientLayer.mask = maskLayer
        } else {
            gradientLayer.mask = nil
        }
    }
}
